﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;

namespace SharePointClientHelper
{
    internal delegate void InvokeDelegate(object args);
    public partial class AddUsers : System.Windows.Forms.Form
    {
        #region 'Private Member Variables'
        private Thread m_workThread = null;
        private SynchronizationContext m_sync = null;
        private DataTable dtUsers;
        #endregion
        
        public AddUsers()
        {
            InitializeComponent();
            SPClientHelper spcHelper = SPClientHelper.GetSPClientHelper();
            List<MyGroup> lstMyGroups = spcHelper.GetSiteGroups();

            ddlGroup.DataSource = lstMyGroups;
            ddlGroup.DisplayMember = "Title";
            ddlGroup.ValueMember = "ID";

            m_sync = SynchronizationContext.Current;
        }

        private void btnAddUsers_Click(object sender, EventArgs e)
        {
            m_workThread = new Thread(new ParameterizedThreadStart(AddUsersFromCSV));
            if (!string.IsNullOrEmpty(openFileDialog1.FileName))
            {
                dtUsers = CSVReader.GetDataSet(openFileDialog1.FileName);
                SPClientHelper spcHelper = SPClientHelper.GetSPClientHelper();
                if (dtUsers.Columns.Contains("GroupName"))
                {
                    m_workThread.Start(true);
                    progressBarAddUser.Visible = true;
                    EnableDisable(false);
                }
                else if (ddlGroup.SelectedIndex > 0)
                {
                    m_workThread.Start(false);
                    progressBarAddUser.Visible = true;
                    EnableDisable(false);
                }
                else
                {
                    MessageBox.Show("Csv doesn't have group name. Please select group name from dropdown");
                }
            }
            else
            {
                MessageBox.Show("Please select csv file.");
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DialogResult diagRes = openFileDialog1.ShowDialog();
            if (diagRes == System.Windows.Forms.DialogResult.OK)
            {
                linkLabel1.Text = openFileDialog1.FileName;
                dtUsers = CSVReader.GetDataSet(openFileDialog1.FileName);
                if (!dtUsers.Columns.Contains("GroupName"))
                {
                    lblSelectGroup.Visible = true;
                    ddlGroup.Visible = true;
                }
            }
        }

        private void AddUsersFromCSV(object args)
        {
            bool hasCsvGroup = Convert.ToBoolean(args);
            SPClientHelper spcHelper = SPClientHelper.GetSPClientHelper();
            List<UpdatedUsers> listUpdatedUsers = new List<UpdatedUsers>();
            if (hasCsvGroup)
            {              
                DataView dvGroups = new DataView(dtUsers, "", "", DataViewRowState.CurrentRows);
                DataTable dtGroups = dvGroups.ToTable(true, new string[] { "GroupName" });
                
                foreach (DataRow dr in dtGroups.Rows)
                {
                    string GroupName = Convert.ToString(dr["GroupName"]);

                    var usersInGroup = (from u in dtUsers.Select("GroupName='" + GroupName + "'").AsEnumerable()
                                        select new MyUser()
                                        {
                                            Name = Convert.ToString(u["Name"]),
                                            EmailId = Convert.ToString(u["EmailId"])
                                        });
                    if (usersInGroup != null)
                    {
                        List<UpdatedUsers> users = spcHelper.UpdateUserInGroup(GroupName, usersInGroup.ToList());
                        listUpdatedUsers.AddRange(users);
                        m_sync.Post(new SendOrPostCallback(SyncMarshalled), listUpdatedUsers);
                    }
                }
            }
            else
            {
                MyGroup group = (MyGroup)ddlGroup.SelectedItem;

                var users = (from u in dtUsers.AsEnumerable()
                                            select new MyUser()
                                            {
                                                Name = Convert.ToString(u["Name"]),
                                                EmailId = Convert.ToString(u["EmailId"])
                                            }).ToList();

                List<UpdatedUsers> objusers = spcHelper.UpdateUserInGroup(group.Title, users);
                listUpdatedUsers.AddRange(objusers);
                m_sync.Post(new SendOrPostCallback(SyncMarshalled), listUpdatedUsers);
            }
        }

        private void SyncMarshalled(object args)
        {
            List<UpdatedUsers> listUpdatedUsers = (List<UpdatedUsers>)args;
            int Total = dtUsers.Rows.Count;
            int percent = listUpdatedUsers.Count * 100 / Total;
            progressBarAddUser.Value = percent;
            if (percent == 100)
            {
                dgvUsers.DataSource = listUpdatedUsers;
                progressBarAddUser.Visible = false;
                EnableDisable(true);
            }
        }

        private void EnableDisable(bool enabled)
        {
            btnAddUsers.Enabled = enabled;
            ddlGroup.Enabled = enabled;
            linkLabel1.Enabled = enabled;
        }
    }
}
